package org.flowable.app.cusTaskExe;

import cmbchina.util.*;
import cmbchina.util.db.FlowDb;
import cmbchina.util.db.FlowFormDb;
import cmbchina.util.http.DbServiceRequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.flowable.app.model.runtime.CompleteFormRepresentation;
import org.flowable.engine.TaskService;
import org.flowable.task.service.delegate.DelegateTask;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by sevenlm on 2017/12/22.
 */
public class CusSpecialScriptTask implements CusTask {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(CusSpecialScriptTask.class);
    @Override
    public AjaxJson exe( CompleteFormRepresentation completeTaskFormRepresentation, TaskService taskService, String taskId, String resultParmas, String processInstId,String taskDefinitionKey) {
        FlowScriptRunUtils scriptRunUtils = new FlowScriptRunUtils();
        //将流程状态置为运行中
        FlowDb.updateFlowState(2, processInstId);
        AjaxJson ajaxJson =new AjaxJson();
        try {
            String script = "";
            if(!completeTaskFormRepresentation.getValues().containsKey("scriptId")){
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("该任务步骤没有配置脚本");
                LOGGER.info("该任务步骤没有配置脚本");
                FlowDb.updateFlowState(4, processInstId);

                //将任务节点改为失败 9527代表任务没有配置脚本
                FlowFormDb.updateFlowFormState(4,processInstId,taskDefinitionKey,"9527",ajaxJson.getMsg(),script);
                taskService.setVariableLocal(taskId, "result", ajaxJson.getMsg());
                return ajaxJson;
            }

            LOGGER.info("test====================================");
            String scriptName = completeTaskFormRepresentation.getValues().get("scriptId").toString();

            //处理脚本
            for(String key:completeTaskFormRepresentation.getValues().keySet()){

                if("whiteListPassord".equals(key)){
                    String password = "";
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String currentDate = sdf.format(new Date());
                    String hostname = completeTaskFormRepresentation.getValues().get("hostname").toString();
                    if(SystemCacheUtil.hostNameMap.containsKey(hostname+currentDate)){
                        password = SystemCacheUtil.hostNameMap.get(hostname+currentDate);
                    }else{
                        password = generatePassword();
                        SystemCacheUtil.hostNameMap.put(hostname+currentDate,password);
                    }
                    scriptName = scriptName.replaceAll("#"+key+"#",password);
                }else{
                    scriptName = scriptName.replaceAll("#"+key+"#",completeTaskFormRepresentation.getValues().get(key)!=null?completeTaskFormRepresentation.getValues().get(key).toString():"");
                }

            }
            script = scriptName;
            //跟新缓存
            ScriptResult scriptResult = new ScriptResult();

            scriptResult = scriptRunUtils.runScript(script);
            taskService.setVariable(taskId,"returnCode",scriptResult.getReturnCode());
            taskService.setVariableLocal(taskId, "result", scriptResult.getResult());
            taskService.setVariableLocal(taskId, "scriptShCommon", script);
            LOGGER.info("配置了输出："+resultParmas);

            if(scriptResult.getReturnCode()!=0){
                ajaxJson.setSuccess(false) ;
                ajaxJson.setCode(scriptResult.getReturnCode()+"");
                ajaxJson.setMsg(scriptResult.getResult()+"");
                if(resultParmas!=null&&!"".equals(resultParmas)){
//                    ajaxJson.setSuccess(true) ;
                    taskService.setVariable(taskId,resultParmas,scriptResult.getReturnCode());
                }
                //将任务节点改为失败
                FlowFormDb.updateFlowFormState(4,processInstId,taskDefinitionKey,scriptResult.getReturnCode()+"",scriptResult.getResult(),script);
            }
            else{
                ajaxJson.setSuccess(true);
                ajaxJson.setCode(scriptResult.getReturnCode()+"");
                ajaxJson.setMsg(scriptResult.getResult()+"");
                //将任务节点改为成功
                FlowFormDb.updateFlowFormState(5,processInstId,taskDefinitionKey,scriptResult.getReturnCode()+"",scriptResult.getResult(),script);
            }

        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.setSuccess(false) ;
            ajaxJson.setCode("400");
            ajaxJson.setMsg(e.getMessage());
            //将任务节点改为失败
            FlowFormDb.updateFlowFormState(4,processInstId,taskDefinitionKey,ajaxJson.getCode()+"",ajaxJson.getMsg(),"");
            taskService.setVariable(taskId, "returnCode", "10000");
            taskService.setVariableLocal(taskId, "result", e.getMessage());
//            formService.saveFormInstanceByFormModelId(completeTaskFormRepresentation.getValues(), completeTaskFormRepresentation.getFormId(), taskId, task.getProcessInstanceId());
        }
        if(ajaxJson.isSuccess() || (resultParmas!=null&&!"".equals(resultParmas))){
            taskService.completeTaskWithForm(taskId, completeTaskFormRepresentation.getFormId(),
                    completeTaskFormRepresentation.getOutcome(), completeTaskFormRepresentation.getValues());
//            taskService.createTaskQuery().processInstanceId(processInstId).singleResult();
//            taskService.createTaskQuery().processInstanceId(processInstId).singleResult().get;

            LOGGER.info("task count"+taskService.createTaskQuery().processInstanceId(processInstId).count());
            if(FlowFormDb.isEnd(processInstId)){
                LOGGER.info("=======判断是否执行完成====");
                int state = ajaxJson.isSuccess()?5:4;
                //将流程状态置为运行成功
                FlowDb.updateFlowState(state, processInstId);
            }else{
                LOGGER.info("=======判断是否执行完成====");
                int state = ajaxJson.isSuccess()?5:4;
                //将流程状态置为运行成功
                FlowDb.updateFlowState(state, processInstId);
            }
        }else{
            //将流程状态置为运行失败
            FlowDb.updateFlowState(4, processInstId);
        }
        return ajaxJson;
    }


    public static String generatePassword(){
        String a = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] rands = new char[6];
        for (int i = 0; i < rands.length; i++)
        {
            int rand = (int) (Math.random() * a.length());
            rands[i] = a.charAt(rand);
        }
        char[] rands1 = new char[2];
        a="!@#$%^&*()_+{}|<>?";
        for (int i = 0; i < rands1.length; i++)
        {
            int rand = (int) (Math.random() * a.length());
            rands1[i] = a.charAt(rand);
        }

        return String.valueOf(rands)+String.valueOf(rands1);
    }
}
